import Web3 from "web3";
import contractJson from './contract/contract.json';

const contractAddr = "0x5e9bF62fF9EB10E80511a351E7Ee251208164513";

export default function useWeb3() {
    // 直接使用主节点配置
    const web3 = window.ethereum ? new Web3(window.ethereum) : null;

    // 如果没有成功连接到主节点，则无法继续，所以这里不进行备用节点切换
    if (!web3) {
        throw new Error('No web3 instance injected, or no Ethereum provider found.');
    }
    // 创建智能合约实例
    const contract = new web3.eth.Contract(contractJson.abi, contractAddr);

    // 定义与智能合约交互的函数
    const getItems = async (itemId) => {
        return contract.methods.getItem(itemId).call();
    };
    const fetchItems = async () => {
        return contract.methods.nextItemId().call();
    };

    return {
        web3,
        contract,
        getItems,
        fetchItems
    };
}